﻿using System;
using System.Collections.Generic;
using System.Text;
using VideoCache.Aggregation.Interfaces;
using Fsb.Utility;

namespace VideoCache.Aggregation.Implements
{
    [Site("iqiyi.com")]
    class IQiyiFetcher
    {
        public string GetToken(string url)
        {
            string token = this.GetTokenByUrl(url);

            if (string.IsNullOrEmpty(token))
            {
                return this.GetTokenByPlayer(url);
            }

            return token;
        }

        private string GetTokenByUrl(string url)
        {
            string html = HttpUtility.Get(url, Encoding.UTF8);

            string token = StringUtility.SubString(html, "data-player-videoid=\"", "\"");

            if (string.IsNullOrEmpty(token))
            {
                string json = StringUtility.SubString(html, "var info=", "</script>");
                if (!string.IsNullOrEmpty(json))
                {
                    Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(json);

                    return jObject["videoId"].ToString().Trim('\"');
                }
            }

            return token;
        }

        private string GetTokenByPlayer(string url)
        {
            return UrlHelper.GetParameter(url, "vid");
        }
    }
}
